<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #canvas {
            background: rebeccapurple;
        }
    </style>
</head>
<body>

<div style="border: solid 1px darkgreen">
    <canvas id="canvas"></canvas>
    <a href="javascript:void(0);" id="downMoveBtn">下移</a>
    <a href="javascript:void(0);" id="topMoveBtn">上移</a>
</div>

<script>
    const canvas = document.getElementById('canvas')
    const topMoveBtn = document.getElementById("topMoveBtn");
    const downMoveBtn = document.getElementById("downMoveBtn");
    canvas.width = 800
    canvas.height = 800
    const ctx = canvas.getContext('2d')

    let y = 200;
    const img = new Image();
    img.src = './images/radar_car_left.png';
    img.onload = function () {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.save();
        ctx.drawImage(img, 200, y, 50, 50);
        ctx.restore();
    }

    downMoveBtn.onclick = function () {
        y = y + 10;
        drawImgByMove(y)
    }

    topMoveBtn.onclick = function () {
        y = y - 10;
        drawImgByMove(y)
    }

    function drawImgByMove(y) {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(img, 200, y, 50, 50);
    }

    /**
     * 计算相对于canvas左上角的坐标值
     */
    function windowToCanvas(x, y) {
        const box = canvas.getBoundingClientRect();
        return {
            'x': x - box.left,
            'y': y - box.top
        }
    }
</script>
</body>
</html>
